package gateway.behaviours;

import java.util.LinkedList;

import jade.core.AID;
import jade.core.Agent;
import jade.core.behaviours.CyclicBehaviour;
import jade.lang.acl.ACLMessage;

import com.Event;

import gateway.ontology.GatewayOntology;
import gateway.ontology.classes.basic_translation.Message;
import gateway.ontology.classes.basic_translation.ReceivedMessage;

public class ACLMessageSenderBehaviour extends CyclicBehaviour {

	private LinkedList<EventWrapper> events = new LinkedList<EventWrapper>();

	public ACLMessageSenderBehaviour(Agent agent) {
		super(agent);
	}

	@Override
	public void action() {
		EventWrapper eventWrapper = null;

		synchronized (events) {
			while ((eventWrapper = events.poll()) == null) {
				try {
					events.wait();
				} catch (InterruptedException e) {
					// do nothing
				}
			}
		}

		ACLMessage info = null;
		try {
			AID agentID = eventWrapper.getAgent();
			Event event = eventWrapper.getEvent();

			info = new ACLMessage(ACLMessage.INFORM);
			info.addReceiver(agentID);
			info.setLanguage(myAgent.getContentManager().getLanguageNames()[0]);
			info.setOntology(GatewayOntology.ONTOLOGY_NAME);
			String mapsID = event.getSourceID();
			jade.util.leap.ArrayList params = event.getAllParams();

			Message message = new Message();
			message.setAgentAID(agentID);
			message.setMapsID(mapsID);
			message.setMsgName(event.getName());
			message.setMsgType(event.getType());
			message.setParameters(params);

			ReceivedMessage rm = new ReceivedMessage();
			rm.setMessageWithHeader(message);

			myAgent.getContentManager().fillContent(info, rm);
		} catch (Exception ex) {
			ex.printStackTrace();
		}

		if (info != null) {
			myAgent.send(info);
		}
	}

	public void put(Event event, AID agentID) {
		synchronized (events) {
			events.add(new EventWrapper(event, agentID));
			events.notifyAll();
		}
	}

	private class EventWrapper {
		private Event event;
		private AID agentID;

		public EventWrapper(Event event, AID agentID) {
			this.event = event;
			this.agentID = agentID;
		}

		public Event getEvent() {
			return event;
		}

		public AID getAgent() {
			return agentID;
		}
	}

}
